package com.saint.tvtest.Utils;




import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * Created by Administrator on 2017/12/27.
 */

public class HttpUtil {
    private static HttpService httpService;
    private static OkHttpClient.Builder client;
//    private static String baseUrl;

    public static HttpService getInstance(String baseUrl) {


        synchronized (HttpUtil.class) {
            if (null == httpService) {
                initOkHttpClient();
                Retrofit retrofit = new Retrofit.Builder()
                        .baseUrl(baseUrl)
                        .addConverterFactory(ScalarsConverterFactory.create())
//                        .addConverterFactory(GsonConverterFactory.create())
                        .client(client.build())
                        .build();

                httpService = retrofit.create(HttpService.class);
            }
        }
        return httpService;
    }

//    /**
//     * 配置请求参数方法
//     *
//     * @param postParams 请求参数
//     * @return 排序并加上签名的map集合
//     */
//    public static HashMap<String, String> getParamMap(Activity act, HashMap<String, String> postParams) {
//        return getParamMap(act, postParams, false);
//    }


    /**
     * 设置OkHttpClient 忽略https验证
     */
    private static void initOkHttpClient() {
        client = new OkHttpClient.Builder();

        X509TrustManager xtm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                X509Certificate[] x509Certificates = new X509Certificate[0];
                return x509Certificates;
            }
        };

        SSLContext sslContext = null;
        try {
            sslContext = SSLContext.getInstance("SSL");

            sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom());
            client.sslSocketFactory(sslContext.getSocketFactory());
            client.hostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }

    }




}
